﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;

public class Singleton<T> where T: class
{
    private static T instance;
    private static readonly Object lockObj=new Object();
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                try { 
                    Monitor.Enter(lockObj);
                    {
                        if (instance == null)
                        {
                            instance =System.Activator.CreateInstance<T>();
                        }
                    }
                }
                finally
                {
                    Monitor.Exit(lockObj);
                }
            }
            return instance;
        }
    }
}
public class MonoSingleton<T>:MonoBehaviour where T : MonoSingleton<T>
{
    private static T instance;
    private static readonly object lockObj = new object();
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                try
                {
                    Monitor.Enter(lockObj);
                    instance = FindObjectOfType(typeof(T)) as T;
                    if (instance == null)
                    {
                        instance = new GameObject(typeof(T).Name,typeof(T)).GetComponent<T>();
                    }
                }
                finally
                {
                    Monitor.Exit(lockObj);
                }
            }
            return instance;
        }
    }
}